package com.YCH.login.service.Impl;

import com.YCH.login.service.TbUserLoginService;
import com.YCH.model.common.dtos.ResponseResult;
import com.YCH.model.common.enums.AppHttpCodeEnum;
import com.YCH.model.mappers.app.TbUserMapper;
import com.YCH.model.user.pojos.TbUser;
import com.YCH.utils.jwt.AppJwtUtil;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@SuppressWarnings("all")
public class TbUserLoginServiceImpl implements TbUserLoginService {

    @Autowired
    private TbUserMapper apUserMapper;

    @Override
    public ResponseResult loginAuth(TbUser user) {
        //验证参数
        if (StringUtils.isEmpty(user.getMobile()) && StringUtils.isEmpty(user.getEmail()) || StringUtils.isEmpty(user.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询用户
        TbUser dbUser = apUserMapper.selectByApPhone(user.getMobile());
        TbUser dbUser2 = apUserMapper.selectByApEmail(user.getEmail());
        if (dbUser == null && dbUser2 == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        Map<String, Object> map = Maps.newHashMap();
        //密码错误
        if(dbUser == null){
            if (!user.getPassword().equals(dbUser2.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            dbUser2.setPassword("");
            map.put("token", AppJwtUtil.getToken(dbUser2));
            map.put("user", dbUser2);
        }else {
            if (!user.getPassword().equals(dbUser.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            dbUser.setPassword("");
            map.put("token", AppJwtUtil.getToken(dbUser));
            map.put("user", dbUser);
        }
        return ResponseResult.okResult(map);
    }
}
